package com.mymoney.ws.asynctasks;

import java.util.ArrayList;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.mymoney.MyMoneyActivity;
import com.mymoney.constants.RequestPaths;
import com.mymoney.data.access.JsonParser;
import com.mymoney.exceptions.CommunicationException;
import com.mymoney.ws.client.SSLHttpClient;
import com.mymoney.ws.data.ItemBean;

/**
 * AsyncTask that call RegisterDevice web service
 *
 * @author dimitar.zlatkov
 */
public abstract class UpdateItemAsyncTask extends AsyncTask<String, Void, Void> {

    private static String TAG = "UpdateItemAsyncTask";
    private Context context;
    private ItemBean item;
    private ArrayList<String> errorList;

    public ArrayList<String> getErrorList() {
		return errorList;
	}

	public UpdateItemAsyncTask(MyMoneyActivity context, ItemBean item) {
        this.context = context;
        this.item = item;
    }

    @Override
    protected Void doInBackground(String... arg0) 
    {
        Log.i(TAG, "UpdateItemAsyncTask on background start...");
        if(this.item != null)
        {
        
	        SSLHttpClient httpClient = new SSLHttpClient(context);
	
	        String path = RequestPaths.getInstance().createModifyItemPath(Long.toString(this.item.getCode()));
	        
	        this.item.setBought(1);
	        
	        String requestBody = JsonParser.getInstance().toJSON(this.item);
	        try {
	        	
	            httpClient.put(path, requestBody);
	
	        }
	        catch (CommunicationException e) {
	        	errorList.add(e.getMessage());
			}
	        catch (Exception e) {
	            Log.e(TAG, "Immediate internal error", e);
	        }
        }
            
            return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        onFinish();
    }

    public abstract void onFinish();
}
